<script setup>
import { defineComponent, onMounted, ref, watch } from 'vue'

const props = defineProps({
  value: [String, Number, Boolean, Array],
  prop: String,
  refName: String,
  options: Array,
  valueFiled: { // 当后端返回的value属性名不一样的情况下 可通过这个属性重新设置显示的属性名
    type: String,
    default: 'value',
  },
  labelFiled: {
    type: String,
    default: 'label',
  },
  defaultSlot: Object,
  prefix: Object,
  empty: Object,
  isGroup: { // 是否分组显示
    type: Boolean,
    default: false
  },
  change: {
    type: Function,
    default: () => {}
  },
  visibleChange: {
    type: Function,
    default: () => {}
  },
  blur: {
    type: Function,
    default: () => {}
  },
  focus: {
    type: Function,
    default: () => {}
  },
  clear: {
    type: Function,
    default: () => {}
  },
  removeTag: {
    type: Function,
    default: () => {}
  }
})

const val = ref(props.value)
watch(() => props.value, newVal => {
  val.value = newVal
})

const emit = defineEmits(['input', 'getRef'])
emit('input', val) // 传递给父组件

const selectRef = ref(null)
const name =  props.refName || `${props.prop}Ref`
onMounted(() => {
  emit('getRef', { name, value: selectRef.value })
})

const dSlot = defineComponent(props.defaultSlot)
const prefixSlot = defineComponent(props.prefix)
const emptySlot = defineComponent(props.empty)
</script>

<template>
  <el-select
    ref="selectRef"
    v-model="val"
    v-bind="$attrs"
    @change="change"
    @visible-change="visibleChange"
    @blur="blur"
    @focus="focus"
    @clear="clear"
    @remove-tag="removeTag">
    <template v-if="isGroup">
      <el-option-group v-for="group in options" :key="group[labelFiled]" :label="group[labelFiled]" :disabled="group.disabled">
        <el-option v-for="item in group.options" :key="item[valueFiled]" :label="item[labelFiled]" :value="item[valueFiled]" :disabled="item.disabled"></el-option>
      </el-option-group>
    </template>
    <template v-else>
      <el-option v-for="item in options" :key="item[valueFiled]" :label="item[labelFiled]" :value="item[valueFiled]" :disabled="item.disabled"></el-option>
    </template>
    <template v-if="defaultSlot">
      <dSlot />
    </template>
    <template #prefix v-if="prefix">
      <prefixSlot />
    </template>
    <template #empty v-if="empty">
      <emptySlot />
    </template>
  </el-select>
</template>

<style scoped>
.el-select{
  width: 100%;
}
</style>
